import threading
import time
import traceback

from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
from apscheduler.schedulers.blocking import BlockingScheduler

from api import tests, jobs


class ProdSchedule(threading.Thread):
    __instance = None

    def __init__(self):
        super().__init__()
        self.setName('scheduler')
        self.scheduler = BlockingScheduler()

    def begin(self):
        if not self.is_alive():
            self.setDaemon(False)
            self.start()

    def shutdown(self):
        self.scheduler.shutdown(wait=False)

    @classmethod
    def stop(cls):
        if cls.__instance:
            cls.__instance.shutdown()
            print('任务调度线程退出')
        else:
            print("任务调度实例不存在")

    @classmethod
    def new_instance(cls):
        cls.__instance = ProdSchedule()
        return cls.__instance

    @classmethod
    def get_instance(cls):
        return cls.__instance

    def run(self):
        self.scheduler.add_listener(job_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
        self.scheduler.add_job(jobs.clear_sample_record, 'cron', day_of_week=6)
        try:
            self.scheduler.start()
        except (KeyboardInterrupt, SystemExit):
            traceback.print_exc()


def job_listener(event):
    if event.exception:
        traceback.print_exc()
    else:
        print("开始运行定时任务")


if __name__ == '__main__':
    scheduler_thread = ProdSchedule.new_instance()
    scheduler_thread.begin()
    time.sleep(5)
    scheduler_thread.scheduler.add_job(tests.tick, 'interval', seconds=3)
